import java.util.Arrays;
import java.util.Random;

/**
 * @projectName: AppProject
 * @package: PACKAGE_NAME
 * @className: Work2
 * @author: Kvzjj
 * @description: TODO
 * @date: 2023/9/13 8:21
 * @version: 1.0
 */
//找出一个整数数组中子数组之和的最大值，
// 例如：数组[1, -2, 3, 5, -1]，返回8（因为符合要求的子数组是 [3, 5]）；
// 数组[1, -2, 3, -8, 5, 1]，返回6（因为符合要求的子数组是 [5, 1]）;
// 数组[1, -2, 3,-2, 5, 1]，返回7（因为符合要求的子数组是 [3, -2, 5, 1]）。
public class Work2 {
    public static void main(String[] args) {
        int[] array1 = {1, -2, 3, 5, -1};
        int[] array2 = {1, -2, 3, -8, 5, 1};
        int[] array3 = {1, -2, 3, -2, 5, 1};

        int[] array4=generateRandomIntArray(10);
        int maxSum1 = findMaxSubarraySum(array1);
        int maxSum2 = findMaxSubarraySum(array2);
        int maxSum3 = findMaxSubarraySum(array3);


        System.out.println("数组1的最大子数组和为: " + maxSum1);
        System.out.println("数组2的最大子数组和为: " + maxSum2);
        System.out.println("数组3的最大子数组和为: " + maxSum3);
        System.out.println(Arrays.toString(array4));
        int maxSum4=findMaxSubarraySum(array4);
        System.out.println("随机数组的最大子数组之后： "+maxSum4);
    }

    public static int findMaxSubarraySum(int[] nums) {
        int maxSum = nums[0];
        int currentSum = nums[0];

        for (int i = 1; i < nums.length; i++) {
            currentSum = Math.max(nums[i], currentSum + nums[i]);
            maxSum = Math.max(maxSum, currentSum);
        }

        return maxSum;
    }
    /**
     * @param size:
     * @return int
     * @author kvzjj
     * @description TODO 生成随机整数数组
     * @date 2023/9/13 8:57
     */
    public static int[] generateRandomIntArray(int size) {
        int[] randomArray = new int[size];
        Random rand = new Random(System.currentTimeMillis());

        for (int i = 0; i < size; i++) {
            randomArray[i] = rand.nextInt(2001) - 1000; // 生成-1000到1000之间的随机整数
        }
        return randomArray;
    }
}
